package cn.itcast.shiro;

import cn.itcast.domain.module.Module;
import cn.itcast.domain.user.User;
import cn.itcast.service.system.ModuleService;
import cn.itcast.service.system.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.List;

public class AuthRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    //授权（获取当前认证用户的所有权限）
    //principalCollection：认证用户
    //AuthorizationInfo: 返回的认证用户具备的所有权限集合
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //获取认证用户具备的权限
        User user = (User)principalCollection.getPrimaryPrincipal();
        List<Module> menus = userService.findMenus(user);
        //将所有权限名放入set集合中
        HashSet hashSet = new HashSet();
        for (Module module : menus) {
            hashSet.add(module.getName());
        }
        //将set集合装入SimpleAuthorizationInfo对象返回
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.setStringPermissions(hashSet);
        return simpleAuthorizationInfo;
    }

    @Override
    //认证(从数据库中获取安全数据)
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //1、获取uptoken拿着账号名
        UsernamePasswordToken upt = (UsernamePasswordToken) authenticationToken;
        //2、根据email从数据中获取安全数据user对象
        String email = upt.getUsername();
        User user = userService.findByEmail(email);
        if (user != null) {
            //调用密码比较器， 比较 页面的密码和数据库中的安全数据是否一致
            return new SimpleAuthenticationInfo(user,user.getPassword(),this.getName());
            //SimpleAuthenticationInfo 三个参数
            //参数1： 安全数据  user对象
            //参数2： 安全数据的密码  user.getPassword();
            //参数3： 当前realm的名 this.getname();
        }

        return null;//抛出异常
    }
}
